﻿using UnityEngine;
using System.Collections.Generic;
using TableProto;
/// <summary>
/// 摆放货物  生成购物清单
/// </summary>
public class PlaceGoods : MonoSingleton<PlaceGoods>
{
    //所需要购买商品数量    购买商品3-6个随机出现；
    private int goodsCount = 3;
    public int GoodsCount
    {
        get
        {
            return goodsCount;
        }

        set
        {
            goodsCount = value;
        }
    }

    //货物分类区 坐标存储
    Transform vegetablesPoint;
    Transform fruitsUpPoint;
    Transform fruitsDownPoint;
    Transform snacksPoint;
    Transform toyPoint;
    Transform dessertPoint;
    Transform suppliesPoint;
    //Hie面板购买的物品父节点
    //[HideInInspector]
    //public Transform goodsbuyTrans;
    // 存储的都是表的 resid
    List<string> veglist = new List<string>(); //{ "304050402", "304050404", "304050406", "304050408", "304050410", "304050412", "304050414", "304050416", "304050418", "304050420", "304050422" };
    List<string> frulist1 = new List<string>(); //{ "304050434", "304050444", "304050446", "304050424", "304050432", "304050438" };
    List<string> frulist2 = new List<string>(); //{ "304050426", "304050428", "304050442", "304050430", "304050436", "304050440" };    
    List<string> snalist = new List<string>(); //{ "304050448", "304050452", "304050454", "304050460", "304050464", "304050466", "304050450", "304050456", "304050457", "304050458", "304050465", "304050462" };

    const string groupMask = "";

    //货物储存区 存储（随机好的）货物
    List<string> vegArray = new List<string>();
    List<string> fruitUpArray = new List<string>();
    List<string> fruitDownArray = new List<string>();
    List<string> snaArray = new List<string>();

    //新添加三种购物区  玩具  冰激凌   生活用品 ()
    List<string> toyArray = new List<string>();
    List<string> dessertArray = new List<string>();
    List<string> suppliesArray = new List<string>();

    //购买清单 存储商品resid
    [HideInInspector]
    public List<string> goodsBuyList = new List<string>();

    //购买清单 是否购买 string resid   int是完成数量
    [HideInInspector]
    public Dictionary<string, int> goodsBuyDic = new Dictionary<string, int>();

    protected override void Awake()
    {
        guidIndex = -1;

        vegetablesPoint = transform.Find("vegetables");
        fruitsUpPoint = transform.Find("fruitsUp");
        fruitsDownPoint = transform.Find("fruitsDown");
        snacksPoint = transform.Find("snacks");
        toyPoint = transform.Find("toy");
        dessertPoint = transform.Find("dessert");
        suppliesPoint = transform.Find("supplies");

        veglist.Clear();
        frulist1.Clear();
        frulist2.Clear();
        snalist.Clear();

        goodsBuyDic.Clear();
        goodsBuyList.Clear();



        veglist = GoodsInfoModel.Instance.GetItems(GoodsType.Vegetables);
        snalist = GoodsInfoModel.Instance.GetItems(GoodsType.Snacks);
        int index = 0;
        List<string> tempFruits = GoodsInfoModel.Instance.GetItems(GoodsType.Fruits);
        foreach (string item in tempFruits)
        {
            index++;
            if (index < 7)
                frulist1.Add(item);
            else
                frulist2.Add(item);
        }
        Debug.Log(TableProtoLoader.SuperMarketGoodsInfoDict.Count);
        /*foreach (var smgi in TableProtoLoader.SuperMarketGoodsInfoDict.Values)
        {
            if ((GoodsType)smgi.type == GoodsType.Vegetables)
            {
                veglist.Add(smgi.groupId);
            }
            else if ((GoodsType)smgi.type == GoodsType.Fruits)
            {
                index++;
                if (index < 7)
                    frulist1.Add(smgi.groupId);
                else
                    frulist2.Add(smgi.groupId);
            }
            else if ((GoodsType)smgi.type == GoodsType.Snacks)
            {
                snalist.Add(smgi.groupId);
            }
        }*/
        index = 0;
        /*printGroupId(veglist);
        printGroupId(frulist1);
        printGroupId(frulist2);
        printGroupId(snalist);*/
    }

    void printGroupId(List<string> list)
    {
        print(" =========== ");
        foreach (var item in list)
        {
            print(item + " ==== item");
        }
    }
    /// <summary>
    /// 摆放货物 ( 可以多次调用  重新随机分配货物和购物清单 )
    /// </summary>
    public void Place()
    {
        //清除
        ClearAllGoods();

        //蔬菜区
        vegArray.Clear();
        fruitUpArray.Clear();
        fruitDownArray.Clear();
        snaArray.Clear();

        RandomGoods(vegArray, veglist, SuperMarketResPath.Vegetables_Dir, vegetablesPoint);

        //水果 上排区
        RandomGoods(fruitUpArray, frulist1, SuperMarketResPath.FruitUp_Dir, fruitsUpPoint, 3);
        //水果 下排区
        RandomGoods(fruitDownArray, frulist2, SuperMarketResPath.FruitDown_Dir, fruitsDownPoint, 3);

        //零食区
        RandomGoods(snaArray, snalist, SuperMarketResPath.Snacks_Dir, snacksPoint);

        toyArray = GoodsInfoModel.Instance.GetItems(GoodsType.Toy);
        dessertArray = GoodsInfoModel.Instance.GetItems(GoodsType.Dessert);
        suppliesArray = GoodsInfoModel.Instance.GetItems(GoodsType.Supplies);

        ShoppingList();
    }

    void Update()
    {
        //mjbTest
        /*if (Input.GetKeyDown(KeyCode.A))
            ShoppingList();*/
    }

    /// <summary>
    /// 生成购物清单
    /// </summary>
    public void ShoppingList()
    {
        //购买商品3 - 6个随机出现；  假设总值为100，出现3种的频率是15 - 18 %。其他数量频率随机 4 - 6种的出现频率为82 % -85 %
        int[] tempRanArray = { 1, 2, 2, 2, 2, 2 };
        int tempSub = Random.Range(0, tempRanArray.Length);
        if (tempSub == 0)
            GoodsCount = 3;
        else
            GoodsCount = Random.Range(4, 7);
        if (SuperMarketGame.Instance.isFirstPlay)
            GoodsCount = 3;
        //Debug.Log(GoodsCount + "  ===== GoodsCount");
        //随机选三个种类(允许最多两个种类重复)
        List<int> listType = new List<int>();
        if (GoodsCount == 3) //&& SuperMarketGame.Instance.isFirstPlay
        {
            listType.Add(1); listType.Add(2); listType.Add(3);
        }
        /*else if (GoodsCount == 4)
        {
            listType.Add(1); listType.Add(2); listType.Add(3);
            listType.Add(Random.Range(1, 4));
        }
        else if (GoodsCount == 5)
        {
            listType.Add(1); listType.Add(2); listType.Add(3);
            int random = Random.Range(1, 4);
            switch (random)
            {
                case 1:
                    listType.Add(1); listType.Add(2);
                    break;
                case 2:
                    listType.Add(1); listType.Add(3);
                    break;
                case 3:
                    listType.Add(2); listType.Add(3);
                    break;
            }
        }
        else if (GoodsCount == 6)
        {
            listType.Add(1); listType.Add(1); listType.Add(2); listType.Add(2); listType.Add(3); listType.Add(3);
        }
        listType.Sort();*/
        else
        {
            while (listType.Count < GoodsCount)
            {
                int num = Random.Range(1, 7);
                List<int> tempList = listType.FindAll((int index) => index == num);
                //if(tempList != null && tempList.Count > 0)
                //Debug.Log(tempList.Count + " == tempList ===  "+ tempList[0]);
                if (listType.Contains(num) && tempList.Count >= 2)
                    continue;
                else
                {
                    listType.Add(num);
                }
            }
        }
        listType.Sort();
        //在种类里随机选出    购买商品3-6个随机出现；
        goodsBuyList.Clear();
        goodsBuyDic.Clear();
        string tempName = "";
        int vegCount = 0;
        for (int i = 0; i < listType.Count; i++)
        {
            if ((GoodsType)listType[i] == GoodsType.Vegetables)
            {
                //蔬菜
                if (vegCount == 0)
                    tempName = RandomBuyGoods(vegArray, true);
                else
                    tempName = RandomBuyGoods(vegArray);

                vegCount++;
            }
            else if ((GoodsType)listType[i] == GoodsType.Fruits)
            {
                //水果
                int temp = Random.Range(0, 2);
                if (temp == 0)
                {
                    // 水果上
                    tempName = RandomBuyGoods(fruitUpArray);
                }
                else
                {
                    //水果下
                    tempName = RandomBuyGoods(fruitDownArray);
                }
            }
            else if ((GoodsType)listType[i] == GoodsType.Snacks)
            {
                //零食
                tempName = RandomBuyGoods(snaArray);
            }
            else if ((GoodsType)listType[i] == GoodsType.Toy)
            {
                //玩具
                tempName = RandomBuyGoods(toyArray);
            }
            else if ((GoodsType)listType[i] == GoodsType.Dessert)
            {
                //甜点
                tempName = RandomBuyGoods(dessertArray);
            }
            else if ((GoodsType)listType[i] == GoodsType.Supplies)
            {
                //日常用品
                tempName = RandomBuyGoods(suppliesArray);
            }
            goodsBuyList.Add(tempName);
            goodsBuyDic.Add(tempName, 0);
        }
        /*
         toyArray = Go
         dessertArray 
         suppliesArray
         */
        /*print(" === Goods Name === ");
        foreach (var item in goodsBuyList)
        {
            Debug.Log(item);
        }*/
    }

    /// <summary>
    /// 随机生成购买的物品，不重复
    /// </summary>
    /// <param name="randomList"></param>
    /// <param name="isNeedIndex">是否需要物品摆放的index</param>
    /// <returns></returns>
    string RandomBuyGoods(List<string> randomList, bool isNeedIndex = false)
    {
        string goodsName = "";
        while (goodsName == "")
        {
            int temp = Random.Range(0, randomList.Count);
            string goods = randomList[temp];
            //Debug.Log(goods + "  === =  good Name");
            if (!goodsBuyList.Contains(goods))
            {
                goodsName = goods;
                if (isNeedIndex)
                {
                    guidIndex = temp;
                    //Debug.Log(guidIndex + "  ===== RandomBuyGoods guidIndex");
                }
            }
        }
        return goodsName;
    }

    /// <summary>
    /// 随机摆放的物品(不重复)
    /// </summary>
    /// <param name="listPlace">随机到的物品</param>
    /// <param name="listGoods">随机的物品</param>
    /// <param name="path">Res路径</param>
    /// <param name="parent">父级</param>
    /// <param name="count">随机数量</param>
    void RandomGoods(List<string> listPlace, List<string> listGoods, string path, Transform parent, int count = 6)
    {
        while (listPlace.Count < count)
        {
            int temp = Random.Range(0, listGoods.Count);
            //print(temp + "  listGoods.Count == "+ listGoods.Count);         
            if (!listPlace.Contains(listGoods[temp]))
            {
                listPlace.Add(listGoods[temp]);
                string groupResId = GoodsInfoModel.Instance.GetModelByResId(listGoods[temp]).groupId;
                //摆放的是Group 组物品
                string resPath = path + "/" + groupResId + groupMask;
                //Debug.Log(resPath);
                GameObject veg = Instantiate(CommonUtility.LoadPrefab(resPath));
                //Debug.Log(listPlace.Count-1 + "  == parent.name === "+ parent.name);
                veg.transform.SetParent(parent.GetChild(listPlace.Count - 1));
                veg.transform.localPosition = Vector3.zero;
                veg.transform.localRotation = Quaternion.identity;
                if (veg.transform.childCount > 0)
                {
                    for (int i = 0; i < veg.transform.childCount; i++)
                    {
                        veg.transform.GetChild(i).gameObject.AddComponent<ShopItemDragCtrl>();
                    }
                }

                //不能移除，否则 第二次出问题
                //listGoods.RemoveAt(temp);
            }
            if (listPlace.Count == count)
                break;
        }
    }
    /// <summary>
    /// 是否完成购物任务
    /// </summary>
    /// <returns></returns>
    public bool IsFinishShopping()
    {
        int index = 0;
        //Debug.Log("IsFinishShopping");
        foreach (var item in goodsBuyDic)
        {
            int count = GoodsInfoModel.Instance.GetModelByResId(item.Key).count;
            //Debug.Log("count === " + count + "  ,item.Value === " + item.Value);
            if (item.Value != count)  //item == false
                return false;
            else
                index++;
            //Debug.Log(" index ==  " + index);
        }
        //Debug.Log(index + " === index");
        if (index == GoodsCount)
            return true;
        else
            return false;
    }
    /// <summary>
    /// 是否完成某一个产品的购买数量 
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public bool IsFinishBuyName(string name)
    {
        foreach (var item in goodsBuyDic)
        {
            if (item.Key == name)
            {
                int count = GoodsInfoModel.Instance.GetModelByResId(item.Key).count;
                //Debug.Log(" item.Value == " + item.Value + " , count == " + count);
                if (item.Value < count)
                    return false;
                else
                    return true;
            }
        }
        return false;
    }
    /// <summary>
    /// 修改购买商品的数量
    /// </summary>
    /// <param name="name"></param>
    /// <param name="count"></param>
    public void UpdateGoodsBuyDic(string name, int count)
    {
        foreach (var item in goodsBuyDic)
        {
            if (item.Key == name)
            {
                //Debug.Log("before count === " + goodsBuyDic[name]);
                goodsBuyDic[name] = count;
                //Debug.Log("goodsBuyDic[name] === " + goodsBuyDic[name]);
                //Debug.Log("count === " + count);
                break;
            }
        }
    }
    /// <summary>
    ///   清空所有商品
    /// </summary>
    public void ClearAllGoods()
    {
        ClearGoods(vegetablesPoint);
        ClearGoods(fruitsUpPoint);
        ClearGoods(fruitsDownPoint);
        ClearGoods(snacksPoint);
        /*ClearGoods(toyPoint);
        ClearGoods(dessertPoint);
        ClearGoods(suppliesPoint);*/
    }

    public void ClearGoodsType(GoodsType type)
    {
        switch (type)
        {
            case GoodsType.Vegetables:
                ClearGoods(vegetablesPoint);
                break;
            case GoodsType.Fruits:
                ClearGoods(fruitsUpPoint);
                ClearGoods(fruitsDownPoint);
                break;
            case GoodsType.Snacks:
                ClearGoods(snacksPoint);
                break;
            case GoodsType.Toy:
                ClearGoods(toyPoint);
                break;
            case GoodsType.Dessert:
                ClearGoods(dessertPoint);
                break;
            case GoodsType.Supplies:
                ClearGoods(suppliesPoint);
                break;
        }
    }

    void ClearGoods(Transform point)
    {
        for (int i = 0; i < point.childCount; i++)
        {
            if (point.GetChild(i).childCount > 0)
            {
                Transform goods = point.GetChild(i).GetChild(0);
                if (goods != null)
                    Destroy(goods.gameObject);
            }
        }
    }

    public float TotalPrice(string name)
    {
        SuperMarketGoodsInfo smgi;
        float totalPrice = 0;
        for (int i = 0; i < goodsBuyList.Count; i++)
        {
            if (goodsBuyList[i] == name)
            {
                smgi = GoodsInfoModel.Instance.GetModelByResId(goodsBuyList[i]);
                totalPrice += smgi.price * smgi.count;
            }
        }
        return totalPrice;
    }

    int guidIndex = -1;
    public Vector3 GetGuidPosition()
    {
        //z  -1.8
        Debug.Log(guidIndex + "  ===== guidIndex");
        float x=0f, y=0f, z = -1.8f;
        if (guidIndex == -1)
        {
            SuperMarketGame.Instance.guidHand = false;
            return new Vector3(x, y, z);
        }
        if (guidIndex > 2)
            y = 1.1f;
        else
            y = 1.85f;

        if (guidIndex % 3 == 0)
            x = -7f;
        else if (guidIndex % 3 == 1)
            x = -7.641f;
        else if (guidIndex % 3 == 2)
            x = -8.197f;

        return new Vector3(x, y, z);
    }
}